package com.meaningful.design_pattern.chain_of_responsibility.validation;

import java.util.ArrayList;
import java.util.List;

public class ValidatorChain {

    private final List<ValidationHandler> handlers = new ArrayList<>();

    public void validate(Object value) throws ValidatorException {
        ValidatorContext context = new ValidatorContext(value);
        while (true) {
            int currentIndex = context.currentIndex();
            if (currentIndex == handlers.size()) {
                break;
            }
            ValidationHandler handler = handlers.get(currentIndex);
            handler.validate(context.getValue(), context);
            if (currentIndex == context.currentIndex()) {
                break;
            }
        }
        context.throwExceptionIfNecessary();
    }

    public void addLastHandler(ValidationHandler handler) {
        handlers.add(handler);
    }

}
